import { useRequest } from 'ahooks';
import { Layout, Menu, type MenuProps } from 'antd';
import { Content, Footer } from 'antd/es/layout/layout';
import dayjs from 'dayjs';
import { useEffect, useMemo, useState } from 'react';
import { useLocation, useMatches, useNavigate } from 'react-router-dom';

import appService from '@/api/services/appService';
import workbenchService from '@/api/services/workbenchService';
import Scrollbar from '@/components/scrollbar';
import Account from '@/layouts/_common/account';
import { usePathname, useRouteToMenuBadgeFn, useRouter } from '@/router/hooks';
import { useKnowFlattenedRoutes } from '@/router/hooks/use-flattened-routes';
import {
  useWorkBasePermissionRoutes,
  useWorkLegacyPermissionRoutes,
} from '@/router/hooks/use-permission-routes';
import { menuFilter } from '@/router/utils';
import { useConfigActions, useInitializeData } from '@/store/configStore';
import { useSettingActions, useSettings } from '@/store/settingStore';
import { useUserInfo, useUserState } from '@/store/userStore';
import { ThemeLayout, ThemeMode } from '@/types/enum';
import { AppRouteObject } from '@/types/router';

import { NAV_WIDTH, BASE } from '../config';

import NavLogo from './nav-logo';
import {
  TIAN_GONG_ADMIN_WHITELIST,
  TIAN_GONG_ADMIN_ONLY_WHITELIST,
  TIAN_GONG_USER_WHITELIST,
  type TiangongMenuEntry,
} from './tiangong-whitelists';

const { Sider } = Layout;

type Props = {
  closeSideBarDrawer?: () => void;
};
export default function NavVertical(props: Props) {
  const navigate = useNavigate();
  const matches = useMatches();
  const pathname = usePathname();
  // const [value, setValue] = useState({ path: 'app-review', badge: 0 });

  const settings = useSettings();
  const { themeLayout, themeMode, darkSidebar } = settings;
  const { setSettings } = useSettingActions();

  // const routeToMenuFn = useRouteToMenuFn();
  const routeToMenuBadgeFn = useRouteToMenuBadgeFn();
  const permissionRoutes = useWorkBasePermissionRoutes();
  const legacyPermissionRoutes = useWorkLegacyPermissionRoutes();
  const flattenedRoutes = useKnowFlattenedRoutes();
  const initializeData = useInitializeData();
  const { role, username } = useUserInfo();
  const { userInfo } = useUserState();
  const [initialize, setInitialize] = useState<any>({});
  const [selectedKey, setSelectKey] = useState<string>('');
  const [showNavToggle, setShowNavToggle] = useState<boolean>(false);

  const collapsed = useMemo(() => themeLayout === ThemeLayout.Mini, [themeLayout]);
  const isRoot = username === 'root';
  0;
  const location = useLocation();
  const { replace } = useRouter();
  const { fetchInitialInfo } = useConfigActions();

  useEffect(() => {
    getInitialize();
    fetchInitialInfo();
  }, [fetchInitialInfo]);
  const getInitialize = async () => {
    const res = await appService.initialize();
    setInitialize(res);
  };
  const getAppReviewService = () => {
    return initialize.is_knowledge_manager || initialize.is_knowledge_reviewer
      ? getReviewCount().then((result) => [result])
      : Promise.resolve([]);
  };

  const getReviewCount = () => {
    return workbenchService.getReviewCountApi({
      status: '0',
      startTime: dayjs().subtract(7, 'day').format('YYYY-MM-DD HH:mm:ss'),
      endTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
    });
  };
  // const getAppReview = () => {
  //   return appService.getAppReviewList({ page: 1, page_size: 10 });
  // };
  // const getKnowledgeBaseApproval = () => {
  //   return datasetService.knowledgeBaseApprovalList({ page: 1, page_size: 10, app_id: '' });
  // };
  // const getAnnotationsList = () => {
  //   return knowService.getAnnotations({ page: 1, page_size: 10 });
  // };
  // const getWorkbenchService = () => {
  //   return workbenchService.messageDetailApi({
  //     page: 1,
  //     pageSize: 10,
  //     searchText: '',
  //     status: '0',
  //     startTime: dayjs().subtract(7, 'day').format('YYYY-MM-DD HH:mm:ss'),
  //     endTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
  //   });
  // };

  // 使用 useRequest 的立即执行功能
  const { data, run, cancel } = useRequest(getAppReviewService, {
    // 添加 ready 选项确保在条件满足时才执行
    ready: initialize.is_knowledge_manager || initialize.is_knowledge_reviewer,
    // 添加 manual: false 确保自动执行
    manual: false,
    pollingInterval: 10000,
    pollingWhenHidden: false,
  });

  // 确保在条件满足时立即执行请求
  useEffect(() => {
    if (initialize.is_knowledge_manager || initialize.is_knowledge_reviewer) {
      run();
    }
    return () => cancel();
  }, [initialize.is_knowledge_manager, initialize.is_knowledge_reviewer, run, cancel]);

  const totalNumber = (data: any[]) => {
    if (!data || data.length === 0) return 0;
    const items = data.slice(0, 3);
    const properties = ['appTotal', 'knoeledgeTotal', 'annotationTotal'];
    const total = items.reduce((acc, item) => {
      const add = properties.reduce((sum, prop) => {
        const value = item[prop];
        return sum + (typeof value === 'number' ? value : 0);
      }, 0);
      return acc + add;
    }, 0);
    return total > 99 ? '99' : total;
  };

  const maxTotal = (count: any) => {
    if (count === 0) return 0;
    if (count > 99) {
      return '99';
    }
    return count;
  };

  const selectedKeys = useMemo(() => [pathname], [pathname]);

  const menuList = useMemo(() => {
    let menuRoutes: AppRouteObject[] = [];
    if (!initializeData?.license_edition) {
      menuRoutes = [];
    } else if (initializeData?.use_legacy_version) {
      menuRoutes = menuFilter(legacyPermissionRoutes);
    } else {
      menuRoutes = menuFilter(permissionRoutes);
    }
    // const menuRoutes = menuFilter(permissionRoutes);
    let menuWithBadge = routeToMenuBadgeFn(menuRoutes, [
      { path: 'appReviewCenter', badge: data ? totalNumber(data) : 0 },
      { path: 'app-review', badge: (data && maxTotal(data[0]?.appTotal)) || 0 },
      {
        path: 'datasets/knowledge-base-approval',
        badge: (data && maxTotal(data[0]?.knoeledgeTotal)) || 0,
      },
      { path: 'datasets/approval', badge: (data && maxTotal(data[0]?.annotationTotal)) || 0 },
      {
        path: 'messageCenter',
        badge: (data && maxTotal(data[0]?.notificationsTotal)) || 0,
      },
    ]);

    if (!initializeData?.enableMetahuman) {
      menuWithBadge = menuWithBadge.filter((menu: any) => menu.key !== '/metahumanManage');
    }

    // 天工角色菜单过滤
    const isTiangong = Boolean(userInfo?.is_TianGong === true || userInfo?.is_TianGong === 'true');
    if (isTiangong) {
      let whitelist: TiangongMenuEntry[] = [];
      if (role?.code === 'super_admin') {
        whitelist = TIAN_GONG_ADMIN_WHITELIST;
      } else if (role?.code === 'admin') {
        whitelist = TIAN_GONG_ADMIN_ONLY_WHITELIST;
      } else {
        whitelist = TIAN_GONG_USER_WHITELIST;
      }

      const keyInList = (key: string) => whitelist.some((e) => e.key === key);
      const filterMenu = (menus: any[]): any[] =>
        (menus || [])
          .map((m: any) => {
            const keepSelf = keyInList(m.key);
            const keptChildren = m.children ? filterMenu(m.children) : undefined;

            if (keepSelf) {
              const children = m.children
                ? keptChildren && keptChildren.length > 0
                  ? keptChildren
                  : m.children
                : undefined;
              return {
                ...m,
                children,
              };
            }
            if (keptChildren && keptChildren.length > 0) {
              return { ...m, children: keptChildren };
            }
            return null;
          })
          .filter(Boolean);

      return filterMenu(menuWithBadge);
    }

    let finalMenu;

    if (isRoot) {
      finalMenu = menuWithBadge;
    } else if (role?.code === 'super_admin') {
      const filteredMenu = menuWithBadge
        .filter((menu: any) => menu?.key !== '/singleSign')
        .map((menu: any) => {
          if (menu.children) {
            return {
              ...menu,
              children: menu.children.filter((child: any) => child.key !== '/singleSign'),
            };
          }
          return menu;
        });
      finalMenu = filteredMenu;
    } else if (role?.code === 'admin' || initialize.is_knowledge_reviewer) {
      finalMenu = menuWithBadge
        .filter((menu: any) =>
          ['/', '/aiNav', '/messageCenter', '/appReviewCenter', '/tools'].includes(menu.key),
        )
        .map((menu: any) => {
          if (menu.key === '/appReviewCenter') {
            return {
              ...menu,
              children: (menu.children || []).filter((child: any) =>
                [
                  '/appReviewCenter/datasets/knowledge-base-approval',
                  '/appReviewCenter/datasets/approval',
                ].includes(child.key),
              ),
            };
          }
          return menu;
        });
    } else if (initialize.is_knowledge_manager) {
      finalMenu = menuWithBadge
        .filter((menu: any) =>
          ['/', '/aiNav', '/messageCenter', '/appReviewCenter'].includes(menu.key),
        )
        .map((menu: any) => {
          if (menu.key === '/appReviewCenter') {
            return {
              ...menu,
              children: (menu.children || []).filter(
                (child: any) => child.key === '/appReviewCenter/datasets/knowledge-base-approval',
              ),
            };
          }
          return menu;
        });
    } else {
      finalMenu = menuWithBadge.filter((menu: any) => menu.key === '/' || menu.key === '/aiNav');
    }

    return finalMenu;
  }, [
    routeToMenuBadgeFn,
    permissionRoutes,
    legacyPermissionRoutes,
    data,
    role?.code,
    initialize,
    initializeData?.license_edition,
    initializeData?.use_legacy_version,
    initializeData?.enableMetahuman,
    isRoot,
    userInfo,
  ]);

  console.log('最终侧边栏展示的菜单项:', menuList);

  function isPathValid(path: string, routes: any[]): boolean {
    // 递归检查路由及其子路由
    const checkRoute = (route: any) => {
      // console.log("route==============", path, route);

      // if (route.key === '/') {
      //   return true;
      // }
      if (route.key === path) return true;
      if (route.children) {
        return route.children.some(checkRoute);
      }
      return false;
    };

    return routes.some(checkRoute);
  }

  // useEffect(() => {
  //   const normalized = location.pathname.replace(/^\/worklayouts(\/|$)/, '/');
  //   console.log('路由变化:', location.pathname, menuList, isPathValid(normalized, menuList));
  //   if (!isPathValid(normalized, menuList)) {
  //     replace('/403');
  //   }
  // }, [location.pathname]);

  // console.log("permissionRoutes===========", permissionRoutes);

  const [openKeys, setOpenKeys] = useState<string[]>([]);
  useEffect(() => {
    if (!collapsed) {
      if (matches.length !== 3) {
        const keys = matches
          .filter((match) => match.pathname !== '/worklayouts' && match.pathname !== pathname)
          .map((match) => match.pathname);
        setOpenKeys(keys);
      }
    }
  }, [collapsed, matches, pathname]);

  const handleToggleCollapsed = () => {
    setSettings({
      ...settings,
      themeLayout: collapsed ? ThemeLayout.Vertical : ThemeLayout.Mini,
    });
  };

  const onClick: MenuProps['onClick'] = ({ key, domEvent, keyPath }) => {
    domEvent.stopPropagation();
    const nextLink = flattenedRoutes?.find((e) => e.key === key);
    const url = BASE + key;

    if (nextLink?.hideTab && nextLink?.frameSrc) {
      window.open(nextLink?.frameSrc, '_blank');
      return;
    }

    navigate(url);
    props?.closeSideBarDrawer?.();
  };

  const handleOpenChange: MenuProps['onOpenChange'] = (keys) => {
    setOpenKeys(keys);
  };

  const sidebarTheme = useMemo(() => {
    if (themeMode === ThemeMode.Dark) {
      return darkSidebar ? 'light' : 'dark';
    }
    return darkSidebar ? 'dark' : 'light';
  }, [themeMode, darkSidebar]);

  return (
    <Sider
      trigger={null}
      collapsible
      collapsed={collapsed}
      width={NAV_WIDTH}
      theme={sidebarTheme}
      className="!fixed left-0 top-0 z-10 h-screen"
      onMouseEnter={() => {
        setShowNavToggle(true);
      }}
      onMouseLeave={() => {
        setShowNavToggle(false);
      }}
      // style={{ background: '#fff' }}
    >
      <Layout className="jr-step-v2-1 flex h-full flex-col !bg-@brand-color-home !p-2">
        <Content className={`relative ${collapsed && 'w-[70px]'}  rounded-xl bg-white`}>
          <NavLogo
            collapsed={collapsed}
            onToggle={handleToggleCollapsed}
            showNavToggle={showNavToggle}
          />
          <Layout className="flex-1 bg-white ">
            <Content className="bg-white">
              <Scrollbar className="hide-scrollbar h-[81vh] overflow-auto">
                <Menu
                  mode="inline"
                  items={menuList}
                  theme={sidebarTheme}
                  selectedKeys={selectedKeys.map((item) => item.replace(BASE, ''))}
                  openKeys={openKeys}
                  onOpenChange={handleOpenChange}
                  className={`custom-menu !border-none ${collapsed && 'min-menu'}`}
                  onClick={onClick}
                  defaultSelectedKeys={['/']}
                  forceSubMenuRender
                />
              </Scrollbar>
            </Content>
          </Layout>
          <Footer
            style={{
              padding: '0px',
              background: '#fff',
              width: '90%',
              position: 'absolute',
              left: '50%',
              transform: 'translateX(-50%)',
              bottom: '0',
              borderTop: '1px solid #F2F3F5',
            }}
          >
            <Account />
          </Footer>
        </Content>
      </Layout>
    </Sider>
  );
}
